import {createRouter, createWebHashHistory} from 'vue-router'
import {ElMessage} from "element-plus";
import axios from "axios";

const routes = [
    {
        path: '/',
        redirect: "index"
    },
    {
        path: '/index',
        name: 'index',
        redirect: "userInfo",
        component: () => import('@/views/index.vue'),
        children: [
            {
                path: "/pay",
                name: "pay",
                component: () => import('@/views/pay/pay.vue')
            },
            {
                path: "/dept",
                name: "dept",
                component: () => import('@/views/dept/dept.vue')
            },
            {
                path: "/guarantee",
                name: "guarantee",
                component: () => import('@/views/guarantee/guarantee.vue')
            },
            {
                path: "/info",
                name: "info",
                component: () => import('@/views/info/info.vue')
            },
            {
                path: "/stay",
                name: "stay",
                component: () => import('@/views/stay/stay.vue')
            },
            {
                path: "/userInfo",
                name: "userInfo",
                component: () => import('@/views/userInfo/userInfo.vue')
            }
        ]
    },
    {
        path: '/login',
        name: 'login',
        component: () => import('@/views/login.vue')
    },
    {
        path: '/register',
        name: 'register',
        component: () => import('@/views/register.vue')
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

router.beforeEach((to, from, next) => {
    if (to.name == "login" || to.name == "register") {
        localStorage.removeItem('token');
        localStorage.removeItem('userInfo');
        localStorage.removeItem('image');
        next()
    } else {
        if (localStorage.getItem('token') == null) {
            next("/login")
        } else {
            axios({
                url: `http://localhost:8888/user/checkToken`,
                method: "get",
                headers: {
                    token: localStorage.getItem("token")
                }
            }).then((res) => {
                if (res.data) {
                    next()
                } else {
                    ElMessage({
                        message: "请求超时，请重新登录!",
                        type: "warning"
                    })
                    next("/login")
                }
            })
        }
    }
})

export default router
